<template>
  <div>
    <el-button type="primary" size="default" @click="handleDrawer(null)"
      >新增角色</el-button
    >
    <el-table :data="tableData" border stripe>
      <el-table-column label="角色名称" prop="name" width="100" />
      <el-table-column label="角色权限">
        <template #default="scope">
          <el-tag class="m-1" v-for="item in scope.row.permission">
            {{ routeMap[item] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleDrawer(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="确定不是手抖了？"
            confirmButtonText="确认"
            cancelButtonText="取消"
            icon="WarningFilled"
            iconColor="#f90"
            @confirm="handleDel(scope.row, scope.$index)"
          >
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-drawer
      :title="rowData ? '编辑角色' : '新增角色'"
      v-model="drawer"
      direction="rtl"
      size="30%"
      :destroy-on-close="true"
      :show-close="true"
    >
      <RoleForm :edata="rowData" @update:table-data="handleUpdate" />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import RoleForm from "./components/role-form.vue";
import { RoleType } from "../../types/user";
import { ref } from "vue";
import { roleGet, roleDel } from "../../api/user";
import { routeMapTool } from "../../utils/tools";
const tableData = ref<Array<RoleType>>([
  //   { name: "超级管理员", permission: ["/dashboard"] },
]);
const drawer = ref<boolean>(false);
let res = await roleGet();
tableData.value = res.data.results;

// 路由的map数据
// {
//     '/dashboard':'数据可视化'
// }
const routeMap = routeMapTool();

// 删除
const handleDel = (row: RoleType, idx: number) => {
  console.log("删除", row, idx);
  roleDel(row.objectId).then((res) => {
    tableData.value.splice(idx, 1); //删除本地
  });
};

// 编辑
const rowData = ref<RoleType | null>(null); //存放新增、编辑的数据包
const handleDrawer = (row: RoleType | null) => {
  console.log("区分新增、编辑", row);
  drawer.value = true;
  rowData.value = row;
};
const handleUpdate = (newRole: RoleType) => {
  drawer.value = false;
  if (rowData.value) {
    //编辑后，更新本地列表
    for (let i = 0; i < tableData.value.length; i++) {
      if (tableData.value[i].objectId == newRole.objectId) {
        tableData.value[i] = newRole;
        return;
      }
    }
  } else {
    console.log("新增本地列表");

    //新增后，更新本地列表
    tableData.value.push(newRole);
  }
};
</script>

<style scoped></style>
